<template>
  <div style="border: 1px solid #ccc; padding: 45px;">
       <el-form :inline="true" :model="formInline" class="search-form">
        <!-- 第一行 -->
        <el-form-item label="货品">
          <el-input 
            v-model="formInline.Product_Name" 
            placeholder="请输入货品名称/编号" 
            clearable 
            style="width: 150px; height: 32px;"
          />
        </el-form-item>
        <el-form-item label="货品类型">
          <el-select 
            v-model="formInline.Category_Name" 
            placeholder="请选择" 
            clearable
            style="width: 150px; height: 32px;"
          >
            <el-option label="电子产品" value="电子产品" />
            <el-option label="类别一1" value="类别一1" />
            <el-option label="告知好拼" value="告知好拼" />
            <el-option label="低值易耗品" value="低值易耗品" />
          </el-select>
        </el-form-item>
        <el-form-item label="单位">
          <el-select 
            v-model="formInline.Unit_Name" 
            placeholder="请选择" 
            clearable
            style="width: 150px; height: 32px;"
          >
            <el-option label="个" value="个" />
            <el-option label="米" value="米" />
            <el-option label="立方米" value="立方米" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select 
            v-model="formInline.Status" 
            placeholder="请选择" 
            clearable
            style="width: 150px; height: 32px;"
          >
            <el-option label="正常" value="正常" />
            <el-option label="即将到期" value="即将到期" />
            <el-option label="已到期" value="已到期" />
          </el-select>
        </el-form-item>

        <!-- 第二行 -->
        <el-form-item label="仓库名称">
          <el-select 
            v-model="formInline.Warehouse_Name" 
            placeholder="请选择" 
            clearable
            style="width: 150px; height: 32px;"
          >
            <el-option label="仓库1" value="仓库1" />
            <el-option label="1号仓库" value="1号仓库" />
            <el-option label="2号仓库" value="2号仓库" />
            <el-option label="3号仓库" value="2号仓库" />
            <el-option label="4号仓库" value="2号仓库" />
            <el-option label="5号仓库" value="2号仓库" />
            <el-option label="666号仓库" value="主仓库" />
          </el-select>
        </el-form-item>
        <el-form-item label="剩余天数">
          <el-input 
            v-model="formInline.RemainingDays" 
            placeholder="请输入" 
            style="width: 150px; height: 32px;"
          />
        </el-form-item>
        <el-form-item label="货品批次">
          <el-input 
            v-model="formInline.Batch" 
            placeholder="请输入批次" 
            clearable 
            style="width: 150px; height: 32px;"
          />
        </el-form-item>
        <el-form-item label="内部编码">
          <el-input 
            v-model="formInline.Internal_Code" 
            placeholder="请输入内部编码" 
            clearable 
            style="width: 150px; height: 32px;"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item>
          <el-button type="success" @click="onSubmit" style="height: 32px;">查询</el-button>
          <el-button type="info" @click="resetForm" style="height: 32px; margin-left: 10px;">重置</el-button>
        </el-form-item>
      </el-form>
  </div>

  <div style="border: 1px solid #ccc; padding: 45px;">
    <!-- 表格操作按钮 -->
    <div style="margin-bottom: 15px; display: flex; justify-content: flex-end;">
      <el-button type="primary" @click="exportData" style="margin-right: 10px;">
        <el-icon><Download /></el-icon>
        导出
      </el-button>
      <el-button type="success" @click="refreshData">
        <el-icon><Refresh /></el-icon>
        刷新
      </el-button>
    </div>
    
    <el-table 
       :data="tableData" 
       style="width: 100%"
       v-loading="loading"
       :max-height="500"
     >
        <el-table-column type="selection" width="55" fixed="left" />
        <el-table-column type="index" label="序号" width="60" fixed="left" />
        <el-table-column prop="product_Number" label="货品编号" width="120" fixed="left">
          <template #default="scope">
            <span class="product-number-link">{{ scope.row.product_Number }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="product_Name" label="货品名称" width="120" fixed="left" />
        <el-table-column prop="status" label="状态" width="100" fixed="left">
        </el-table-column>
        <el-table-column prop="category_Name" label="货品类型" width="100" />
        <el-table-column prop="specifications" label="规格" width="100" />
        <el-table-column prop="unit_Name" label="单位" width="80" />
        <el-table-column prop="warehouse_Name" label="仓库名称" width="100" />
        <el-table-column prop="storage_Name" label="仓位名称" width="100" />
        <el-table-column prop="internal_Code" label="内部编码" width="120" />
        <el-table-column prop="currentInventory" label="当前库存" width="100" />
        <el-table-column prop="batch" label="批次" width="80" />
        <el-table-column prop="createTime" label="生产日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="maturityDate" label="到期日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.maturityDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="expirationDate" label="保质期" width="120" />
        <el-table-column prop="remainingDays" label="剩余天数" width="100" />
        <el-table-column prop="warningDays" label="预警天数" width="100" />
      </el-table>
  </div>
      <!-- 分页控件 -->
    <div class="pagination-section">
      <el-pagination
        v-model:current-page="Page.PageIndex"
        v-model:page-size="Page.PageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next"
        :total="Page.totalCount"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>
</template>
<script lang="ts" setup>
import { BusinessRed } from '@/http/axiosHelper';
import { onMounted, reactive, ref } from 'vue'
import { Download, Refresh } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

// 格式化日期函数
const formatDate = (dateString: string) => {
  if (!dateString) return '';
  // 将ISO格式的日期字符串转换为本地格式
  const date = new Date(dateString);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

const formInline = reactive({
  Product_Name: '',
  Category_Name: '',
  Unit_Name:'',
  Internal_Code:'',
  Status:'',
  Batch:'',
  Warehouse_Name:'',
  RemainingDays:'',
})

const tableData = ref([]);
const loading = ref(false);

const Page = reactive({
  PageIndex: 1,
  PageSize: 10,
  totalCount: 0,
})

const onSubmit = () => 
{
  loading.value = true;
  
  // 重置页码到第一页
  Page.PageIndex = 1;
  
  // 构建查询参数，过滤空值
  const params = {
    Product_Name: formInline.Product_Name || '',
    Category_Name: formInline.Category_Name || '',
    Unit_Name: formInline.Unit_Name || '',
    Internal_Code: formInline.Internal_Code || '',
    Status: formInline.Status || '',
    Batch: formInline.Batch || '',
    Warehouse_Name: formInline.Warehouse_Name || '',
    RemainingDays: formInline.RemainingDays || '',
    PageIndex: Page.PageIndex,
    PageSize: Page.PageSize
  };

  console.log('查询参数:', params);

  BusinessRed.get("/api/Ledger/GetExpirationDate", { params })
    .then(res => {
      console.log('查询结果:', res);
      if (res.data && res.data.data) {
        tableData.value = res.data.data;
        Page.totalCount = res.data.totalCount || 0;
        console.log('设置表格数据:', tableData.value);
        console.log('设置总数:', Page.totalCount);
      } else {
        console.log('响应数据为空或格式不正确');
        tableData.value = [];
        Page.totalCount = 0;
      }
    })
    .catch(error => {
      console.error('查询失败:', error);
      console.error('错误详情:', error.response?.data);
      console.error('错误状态:', error.response?.status);
      tableData.value = [];
      Page.totalCount = 0;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 重置表单
const resetForm = () => {
  formInline.Product_Name = '';
  formInline.Category_Name = '';
  formInline.Unit_Name = '';
  formInline.Internal_Code = '';
  formInline.Status = '';
  formInline.Batch = '';
  formInline.Warehouse_Name = '';
  formInline.RemainingDays = '';
  onSubmit();
}

// 处理页码变化
const handleCurrentChange = (val: number) => {
  Page.PageIndex = val;
  onSubmit();
}

// 处理每页条数变化
const handleSizeChange = (val: number) => {
  Page.PageSize = val;
  Page.PageIndex = 1; // 重置到第一页
  onSubmit();
}

// 导出数据
const exportData = async () => {
  try {
    console.log('开始导出...');
    
    // 构建导出参数
    const params = {
      Product_Name: formInline.Product_Name || '',
      Category_Name: formInline.Category_Name || '',
      Unit_Name: formInline.Unit_Name || '',
      Internal_Code: formInline.Internal_Code || '',
      Status: formInline.Status || '',
      Batch: formInline.Batch || '',
      Warehouse_Name: formInline.Warehouse_Name || '',
      RemainingDays: formInline.RemainingDays || '',
    };

    console.log('导出参数:', params);

    // 调用后端导出接口
    const response = await BusinessRed.get('/api/Ledger/GetExpirationDateExport', {
      params: params,
      responseType: 'blob'
    });

    console.log('导出响应:', response);
    console.log('响应数据大小:', response.data?.size);

    // 检查响应数据
    if (!response.data || response.data.size === 0) {
      ElMessage.error('导出失败：服务器返回空数据');
      return;
    }

    // 生成文件名
    const fileName = '到期日期查询.xlsx';

    // 生成下载链接并触发下载
    const blob = new Blob([response.data], { 
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
    });
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = fileName;
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();

    // 清理资源
    setTimeout(() => {
      window.URL.revokeObjectURL(url);
      document.body.removeChild(a);
    }, 100);

    ElMessage.success('导出成功');

  } catch (error: any) {
    console.error('导出失败：', error);
    
    // 更友好的错误提示
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录');
    } else if (error.response?.status === 403) {
      ElMessage.error('权限不足，无法导出数据');
    } else if (error.response?.status === 404) {
      ElMessage.error('导出接口不存在，请联系管理员');
    } else if (error.response?.status === 500) {
      ElMessage.error('服务器错误，请稍后重试');
    } else {
      ElMessage.error('导出失败，请检查网络连接或稍后重试');
    }
  }
}

// 刷新数据
const refreshData = () => {
  console.log('刷新数据');
  onSubmit();
}

onMounted(() => {
  onSubmit();
})
</script>









